package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import jsyf.oa.dao.system.*;
import jsyf.oa.entity.system.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import jsyf.com.util.DateUtils;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.facade.system.SignInFacade;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;


/**
 * Created by WHH-PC on 2018/1/8.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class SignInService implements SignInFacade {
    @Autowired
    private SignInDao signInDao;
    @Autowired
    private LeaveDao leaveDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private DepartDao departDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private TipDao tipDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;


    @Override
    public String revertIn(String jsonData) {
        SignInEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), SignInEntity.class);
        return signInDao.removeById(entity.getId()).toString();
    }

    @Override
    public String revert(String jsonData) {
        SignInEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), SignInEntity.class);
        signInDao.updateTime(entity.getId());
        return entity.getId();
    }


    @Override
    public String save(String jsonData) {
        SignInEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), SignInEntity.class);
        entity.setAm(0.5);
        entity.setPm(0.5);
        entity.setCreateUserId(entity.getUserId());
        Calendar calendar = Calendar.getInstance();
        entity.setSignDate(DateUtils.parse(calendar.getTime(), "yyyy-MM-dd"));
        //删除当天的请假信息
        leaveDao.removeByCondition(" AND LEAVE_DATE = ?  AND USER_ID = ? ", new String[]{entity.getSignDate(), entity.getUserId()});
        //查询当天是否已签到
        JSONObject signInJson = getSignInByDay(entity.getUserId(), entity.getSignDate());
        if (signInJson == null) {
            signInDao.add(entity);
            boolean flag = DateUtils.isInDate(calendar.getTime(), "08:30:00", "23:59:59");
            if (flag) {
                //查询消息
                JSONObject result = new JSONObject();
                result.put("tipType", "考勤签到");
                List<JSONObject> records = tipDao.getTipByType(result.toJSONString());
                if (records != null && records.size() > 0) {
                    TipEntity tipEntity = (TipEntity) tipDao.convertJson2Entity(records.get(0));
                    if (tipEntity != null && !tipEntity.getContent().isEmpty()) {
                        //企业号:发送迟到消息
                        JSONObject msgObject = new JSONObject();
                        msgObject.put("userIds", entity.getUserId());
                        msgObject.put("content", String.format(SIGNIN_NOTICE, tipEntity.getContent()));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                    }
                }
            }
            JSONObject userJson = userDao.getViewJSONById(entity.getCreateUserId());
            if ("区域经理".equalsIgnoreCase(userJson.getString("roleName"))) {
                //保存消息到消息表t_sys_message
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setCreateUserId(entity.getCreateUserId());
                messageEntity.setCreateTime(messageDao.getCurrentTime());
                messageEntity.setContent("考勤签到");
                messageEntity.setMessageType(3);
                messageEntity.setMainId(entity.getId());
                messageEntity.setDelFlag(0);
                messageEntity.setOpenUrl("/reportForm/newReportForm/daQuSignInApp.html?&userId=" + userJson.getString("id") + "&dateTime=" + entity.getSignDate() + "&msg=0");
                messageEntity.setOpenTitle(String.format(SIGN_PUSH_MESSAGE, userJson.getString("name")));
                messageDao.add(messageEntity);

                //保存第一审核人信息到消息收件人表t_sys_message_receiver
                MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                messageReceiverEntity.setMessageId(messageEntity.getId());
                messageReceiverEntity.setUserId(userJson.getString("parentId"));
                messageReceiverEntity.setUserType(0);
                messageReceiverEntity.setReadFlag(0);
                messageReceiverDao.add(messageReceiverEntity);

                //发送企业微信
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", userJson.getString("parentId"));
                msgObject.put("content", String.format(SIGN_PUSH_MESSAGE_WE, userJson.getString("name"),
                        "http://oa.yingfeng365.com/page" + messageEntity.getOpenUrl() + "&receiverId=" + messageReceiverEntity.getId()));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            }
        } else if (StringUtils.isNotEmpty(entity.getSignOutAddress()) && !"".equals(entity.getSignOutAddress())) {
            //当天已签到过，更新签退信息
            SignInEntity outEntity = (SignInEntity) signInDao.getIBaseEntityById(entity.getId());
            outEntity.setSignOutTime(signInDao.getCurrentTime());
            outEntity.setSignOutUrl(entity.getSignOutUrl());
            outEntity.setSignOutAddress(entity.getSignOutAddress());
            outEntity.setSignOutLongitude(entity.getSignOutLongitude());
            outEntity.setSignOutLatitude(entity.getSignOutLatitude());
            if (!StringUtils.isBlank(entity.getSignOutAlwaysDistance())) {
                outEntity.setSignOutAlwaysDistance(entity.getSignOutAlwaysDistance());
            }
            signInDao.update(outEntity);
            JSONObject userJson = userDao.getViewJSONById(entity.getCreateUserId());
            if ("区域经理".equalsIgnoreCase(userJson.getString("roleName"))) {
                //保存消息到消息表t_sys_message
                MessageEntity messageEntity = new MessageEntity();
                messageEntity.setCreateUserId(entity.getCreateUserId());
                messageEntity.setCreateTime(messageDao.getCurrentTime());
                messageEntity.setContent("今日拜访");
                messageEntity.setMessageType(3);
                messageEntity.setMainId(entity.getId());
                messageEntity.setDelFlag(0);
                messageEntity.setOpenUrl("/reportForm/newReportForm/daQuVisitApp.html?&userId=" + userJson.getString("id") + "&dateTime=" + entity.getSignDate() + "&status=1&msg=0");
                messageEntity.setOpenTitle(String.format(SIGN_OUT_PUSH_MESSAGE, userJson.getString("name")));
                messageDao.add(messageEntity);

                //保存第一审核人信息到消息收件人表t_sys_message_receiver
                MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                messageReceiverEntity.setMessageId(messageEntity.getId());
                messageReceiverEntity.setUserId(userJson.getString("parentId"));
                messageReceiverEntity.setUserType(0);
                messageReceiverEntity.setReadFlag(0);
                messageReceiverDao.add(messageReceiverEntity);
                //发送企业微信
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", userJson.getString("parentId"));
                msgObject.put("content", String.format(SIGN_OUT_PUSH_MESSAGE_WE, userJson.getString("name"),
                        "http://oa.yingfeng365.com/page" + messageEntity.getOpenUrl() + "&receiverId=" + messageReceiverEntity.getId()));
                tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            }
        }
        //可能会有先拜访,再签到的情况 ,需要保存首次拜访与签到的差距
        JSONObject obj = new JSONObject();
        obj.put("userId", entity.getUserId());
        obj.put("signDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        obj.put("signOutAddress", entity.getSignOutAddress());
        saveFirstOrLastVisitDiff(JSON.toJSONString(obj));
        return entity.getId();
    }

    @Override
    public JSONObject getSignInByDay(String userId, String signDate) {
        //查询当天签到信息
        Calendar signOutDate = Calendar.getInstance();
        boolean flag = DateUtils.isInDate(signOutDate.getTime(), "00:00:00", "03:00:00");
        if (flag) {
            signDate = DateUtils.getYesterday();
        }
        List<JSONObject> list = signInDao.getJSONListByCondition(" AND USER_ID = ? AND SIGN_DATE = ? ", new Object[]{userId, signDate});
        return list.size() > 0 ? list.get(0) : null;
    }

    /**
     * 某人、某月考勤列表
     *
     * @param jsonData
     * @return
     */
    @Override
    public List<JSONObject> getSignInList(JSONObject jsonData) {
        String userId = jsonData.get("userId").toString();
        String signInMonth = jsonData.get("signInMonth").toString();
        //获取某月考勤信息
        List<JSONObject> list = signInDao.getJSONListByCondition(" AND USER_ID = ? AND LEFT(SIGN_DATE,7) = ?", new Object[]{userId, signInMonth});
        //返回的集合
        List<JSONObject> dayList = new ArrayList<>();
        //已过去的天数
        List<String> arrayDayList = new ArrayList<>();
        //当前日期
        Calendar c = Calendar.getInstance();
        String month = DateUtils.parse(c.getTime(), "yyyy-MM");
        if (signInMonth.equals(month)) {
            //当月，获取当天是本月的第几天
            Integer days = c.get(Calendar.DAY_OF_MONTH);
            for (Integer i = days; i >= 1; i--) {
                arrayDayList.add(signInMonth + "-" + (i < 10 ? ("0" + i) : i));
            }
        } else {
            //非当月，获取某月最后一天
            Integer lastDay = DateUtils.getLastDayOfMonth(Integer.valueOf(signInMonth.split("-")[0]), Integer.valueOf(signInMonth.split("-")[1]));
            for (Integer i = lastDay; i >= 1; i--) {
                arrayDayList.add(signInMonth + "-" + (i < 10 ? ("0" + i) : i));
            }
        }
        //签到信息赋值
        for (Integer i = 0; i < arrayDayList.size(); i++) {
            String signState = "";
            String day = arrayDayList.get(i);
            JSONObject objResult = new JSONObject();
            objResult.put("id", "");
            objResult.put("signDate", arrayDayList.get(i));
            objResult.put("userId", userId);
            for (Integer j = 0; j < list.size(); j++) {
                if (day.equals(list.get(j).get("signDate"))) {
                    objResult.put("id", list.get(j).get("id"));
                    objResult.put("createTime", DateUtils.parse((Date) list.get(j).get("createTime"), "HH:mm"));
                    objResult.put("address", list.get(j).get("address"));
                    objResult.put("signUrl", list.get(j).get("signUrl"));
                    if (!StringUtils.isBlank(list.get(j).get("signOutTime").toString())) {
                        objResult.put("signOutTime", DateUtils.parse((Date) list.get(j).get("signOutTime"), "HH:mm"));
                        objResult.put("signOutAddress", list.get(j).get("signOutAddress"));
                        objResult.put("signOutUrl", list.get(j).get("signOutUrl"));
                    }
                    signState = "0";//正常
                }
            }
            if (signState.equals("")) {
                //获取请假信息
                List<JSONObject> leaveList = leaveDao.getJSONListByCondition(" AND LEAVE_DATE = ? AND USER_ID = ?", new Object[]{day, userId});
                if (leaveList.size() > 0) {
                    signState = "1";//请假
                    objResult.put("remark", leaveList.get(0).get("remark").toString());
                }
            }
            if (signState.equals("")) {
                signState = "2";//缺勤
            }
            objResult.put("signState", signState);
            dayList.add(objResult);
        }
        return dayList;
    }

    /**
     * 获取某人某天是否签到、某个月的考勤汇总
     *
     * @return
     */
    @Override
    public JSONObject getSignInByUserId(JSONObject jsonObject) {
        String userId = jsonObject.get("userId").toString();
        String month = jsonObject.get("signInMonth").toString();
        JSONObject user = userDao.getViewJSONById(userId);
        String roleId = user.get("roleId").toString();
        Calendar c = Calendar.getInstance();
        String nowDay = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        JSONObject result = signInDao.getSignInByUserId(userId, roleId, month, nowDay);
        Integer shouldCount = Integer.valueOf(result.get("shouldCount").toString());
        Integer signInCount = Integer.valueOf(result.get("signInCount").toString());
        Integer leaveCount = Integer.valueOf(result.get("leaveCount").toString());
        Integer lackCount = shouldCount - signInCount - leaveCount;
        result.put("lackCount", lackCount < 0 ? 0 : lackCount);
        return result;
    }

    /**
     * 大区经理：大区、小区考勤列表
     *
     * @return
     */
    @Override
    public List<JSONObject> getSignInRegionList(JSONObject jsonObject) {
        String userId = jsonObject.get("userId").toString();
        String isToday = jsonObject.get("isToday").toString();
        String signInMonth = jsonObject.get("signInMonth").toString();
        //当前日期
        Calendar c = Calendar.getInstance();
        String today = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        JSONObject jsonUser = userDao.getViewJSONById(userId);
        List<JSONObject> regionlist = signInDao.getRegionListByBigRegionDepartId(jsonUser.get("departId").toString());
        //返回的集合
        List<JSONObject> list = new ArrayList<>();
        for (Integer i = 0; i < regionlist.size(); i++) {
            JSONObject objResult = new JSONObject();
            String signState = "";
            String regionId = regionlist.get(i).get("regionId").toString();
            String managerId = regionlist.get(i).get("managerId").toString();
            String managerRoleName = regionlist.get(i).get("managerRoleName").toString();
            String managerName = regionlist.get(i).get("managerName").toString();
            String regionName = regionlist.get(i).get("regionName").toString();
            objResult.put("regionId", regionId);
            objResult.put("regionName", regionName);
            objResult.put("userId", managerId);
            objResult.put("roleName", managerRoleName);
            objResult.put("name", managerName);
            if (isToday.equals("1")) {
                //获取签到信息，当天
                List<JSONObject> signInList = signInDao.getJSONListByCondition("AND SIGN_DATE = ? AND USER_ID = ?", new Object[]{today, managerId});
                if (signInList.size() > 0) {
                    signState = "0";//正常
                    objResult.put("createTime", DateUtils.parse((Date) signInList.get(0).get("createTime"), "HH:mm"));
                    objResult.put("address", signInList.get(0).get("address"));
                    if (!StringUtils.isBlank(signInList.get(0).get("signOutTime").toString())) {
                        objResult.put("signOutTime", DateUtils.parse((Date) signInList.get(0).get("signOutTime"), "HH:mm"));
                        objResult.put("signOutAddress", signInList.get(0).get("signOutAddress"));
                    }
                }
                if (signState.equals("")) {
                    //获取请假信息
                    List<JSONObject> leaveList = leaveDao.getJSONListByCondition(" AND LEAVE_DATE = ? AND USER_ID = ?", new Object[]{today, userId});
                    if (leaveList.size() > 0) {
                        signState = "1";//请假
                        objResult.put("remark", leaveList.get(0).get("remark").toString());
                    }
                }
                if (signState.equals("")) {
                    signState = "2";//缺勤
                }
                objResult.put("signState", signState);
            } else {
                //获取签到信息，某个月
                JSONObject userJson = userDao.getViewJSONById(managerId);
                JSONObject result = signInDao.getSignInByUserId(managerId, userJson.get("roleId").toString(), signInMonth, today);
                objResult.put("shouldCount", Integer.valueOf(result.get("shouldCount").toString()));
                objResult.put("signInCount", Integer.valueOf(result.get("signInCount").toString()));
                objResult.put("leaveCount", Integer.valueOf(result.get("leaveCount").toString()));
                Integer lackCount = Integer.valueOf(result.get("shouldCount").toString()) - Integer.valueOf(result.get("signInCount").toString()) - Integer.valueOf(result.get("leaveCount").toString());
                objResult.put("lackCount", lackCount);
            }

            list.add(objResult);
        }
        return list;
    }

    /**
     * 区域支持：自己、大区、小区
     *
     * @return
     */
    @Override
    public List<JSONObject> getSignInSupportRegionList(JSONObject jsonObject) {
        String userId = jsonObject.get("userId").toString();
        String isToday = jsonObject.get("isToday").toString();
        String signInMonth = jsonObject.get("signInMonth").toString();
        //当前日期
        Calendar c = Calendar.getInstance();
        String today = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        //返回的集合
        List<JSONObject> list = new ArrayList<>();
        JSONObject userJson = userDao.getViewJSONById(userId);
        //获取区域支持自己的考勤信息
        if (isToday.equals("1")) {
            //当天
            JSONObject todayJsonObject = new JSONObject();
            todayJsonObject.put("regionId", userJson.get("departId").toString());
            todayJsonObject.put("departName", userJson.get("departName").toString());
            todayJsonObject.put("regionName", "");
            todayJsonObject.put("userId", userId);
            todayJsonObject.put("roleName", userJson.get("roleName").toString());
            todayJsonObject.put("name", userJson.get("name").toString());
            //获取签到信息，当天
            String signState = "";
            List<JSONObject> signInList = signInDao.getJSONListByCondition("AND SIGN_DATE = ? AND USER_ID = ?", new Object[]{today, userId});
            if (signInList.size() > 0) {
                signState = "0";//正常
                todayJsonObject.put("createTime", DateUtils.parse((Date) signInList.get(0).get("createTime"), "HH:mm"));
                todayJsonObject.put("address", signInList.get(0).get("address"));
                if (!StringUtils.isBlank(signInList.get(0).get("signOutTime").toString())) {
                    todayJsonObject.put("signOutTime", DateUtils.parse((Date) signInList.get(0).get("signOutTime"), "HH:mm"));
                    todayJsonObject.put("signOutAddress", signInList.get(0).get("signOutAddress"));
                }
            }
            if (signState.equals("")) {
                //获取请假信息
                List<JSONObject> leaveList = leaveDao.getJSONListByCondition(" AND LEAVE_DATE = ? AND USER_ID = ?", new Object[]{today, userId});
                if (leaveList.size() > 0) {
                    signState = "1";//请假
                    todayJsonObject.put("remark", leaveList.get(0).get("remark").toString());
                }
            }
            if (signState.equals("")) {
                signState = "2";//缺勤
            }
            todayJsonObject.put("signState", signState);
            list.add(todayJsonObject);
        } else {
            //某个月
            JSONObject monthJsonObject = new JSONObject();
            monthJsonObject.put("regionId", userJson.get("departId").toString());
            monthJsonObject.put("departName", userJson.get("departName").toString());
            monthJsonObject.put("regionName", "");
            monthJsonObject.put("userId", userId);
            monthJsonObject.put("roleName", userJson.get("roleName").toString());
            monthJsonObject.put("name", userJson.get("name").toString());
            JSONObject signInObject = signInDao.getSignInByUserId(userId, userJson.get("roleId").toString(), signInMonth, today);
            monthJsonObject.put("shouldCount", Integer.valueOf(signInObject.get("shouldCount").toString()));
            monthJsonObject.put("signInCount", Integer.valueOf(signInObject.get("signInCount").toString()));
            monthJsonObject.put("leaveCount", Integer.valueOf(signInObject.get("leaveCount").toString()));
            Integer lackCount = Integer.valueOf(signInObject.get("shouldCount").toString()) - Integer.valueOf(signInObject.get("signInCount").toString()) - Integer.valueOf(signInObject.get("leaveCount").toString());
            monthJsonObject.put("lackCount", lackCount < 0 ? 0 : lackCount);
            list.add(monthJsonObject);
        }
        //获取区域支持负责的所有区域
        List<JSONObject> regionList = signInDao.getSupportRegionList(userId);
        for (JSONObject valJson : regionList.stream().filter(x -> x.get("parentId").toString().equals("0")).collect(Collectors.toList())) {
            if (valJson.get("regionName").equals("大客户")) {
                continue;
            }
            for (JSONObject regionJson : regionList.stream().filter(x -> x.get("parentId").toString().equals(valJson.get("regionId")) || x.get("regionId").toString().equals(valJson.get("regionId"))).collect(Collectors.toList())) {
                JSONObject json = new JSONObject();
                String uid = regionJson.get("userId").toString();
                if (regionJson.get("parentId").toString().equals("0")) {
                    json.put("departName", regionJson.get("regionName").toString());
                } else if (!regionJson.get("parentId").toString().equals("")) {
                    json.put("departName", regionList.stream().filter(x -> x.get("regionId").toString().equals(regionJson.get("parentId").toString())).collect(Collectors.toList()).get(0).get("regionName").toString());
                }
                json.put("regionName", regionJson.get("regionName").toString());
                json.put("roleName", regionJson.get("parentId").toString().equals("0") ? "大区经理" : "区域经理");
                json.put("name", !regionJson.get("userName").toString().equals("") ? regionJson.get("userName").toString() : "空缺");
                json.put("userId", uid);
                if (!StringUtils.isBlank(uid)) {
                    String signState = "";
                    if (isToday.equals("1")) {
                        //获取签到信息，当天
                        List<JSONObject> signInList = signInDao.getJSONListByCondition("AND SIGN_DATE = ? AND USER_ID = ?", new Object[]{today, uid});
                        if (signInList.size() > 0) {
                            signState = "0";//正常
                            json.put("createTime", DateUtils.parse((Date) signInList.get(0).get("createTime"), "HH:mm"));
                            json.put("address", signInList.get(0).get("address"));
                            if (!StringUtils.isBlank(signInList.get(0).get("signOutTime").toString())) {
                                json.put("signOutTime", DateUtils.parse((Date) signInList.get(0).get("signOutTime"), "HH:mm"));
                                json.put("signOutAddress", signInList.get(0).get("signOutAddress"));
                            }
                        }
                        if (signState.equals("")) {
                            //获取请假信息
                            List<JSONObject> leaveList = leaveDao.getJSONListByCondition(" AND LEAVE_DATE = ? AND USER_ID = ?", new Object[]{today, uid});
                            if (leaveList.size() > 0) {
                                signState = "1";//请假
                                json.put("remark", leaveList.get(0).get("remark").toString());
                            }
                        }
                        if (signState.equals("")) {
                            signState = "2";//缺勤
                        }
                        json.put("signState", signState);
                    } else {
                        //获取签到信息，某个月
                        JSONObject managerJson = userDao.getViewJSONById(uid);
                        JSONObject result = signInDao.getSignInByUserId(uid, managerJson.get("roleId").toString(), signInMonth, today);
                        Integer shouldCount = Integer.valueOf(result.get("shouldCount").toString());
                        json.put("shouldCount", shouldCount);
                        json.put("signInCount", Integer.valueOf(result.get("signInCount").toString()));
                        json.put("leaveCount", Integer.valueOf(result.get("leaveCount").toString()));
                        Integer lackCount = shouldCount - Integer.valueOf(result.get("signInCount").toString()) - Integer.valueOf(result.get("leaveCount").toString());
                        json.put("lackCount", lackCount < 0 ? 0 : lackCount);
                    }
                }
                list.add(json);
            }
        }
        return list;
    }

    /**
     * 公司管理层：获取本公司所有部门、大区考勤统计
     *
     * @return
     */
    @Override
    public List<JSONObject> getSignInSalerManagerList(JSONObject jsonObject) {
        String companyId = jsonObject.get("companyId").toString();
        //当前日期
        Calendar c = Calendar.getInstance();
        String today = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        //返回的集合
        List<JSONObject> list = new ArrayList<>();
        //本公司销售部和所有大区
        List<JSONObject> departList = departDao.getJSONListByCondition("  AND COMPANY_ID = ? AND DEL_FLAG = 0 ORDER BY SORT_NO ", new Object[]{companyId});
        for (Integer i = 0; i < departList.size(); i++) {
            String departId = departList.get(i).get("id").toString();
            String departName = departList.get(i).get("name").toString();
            //获取某个部门今天的考勤汇总
            JSONObject departJsonObject = signInDao.getSignInByDepart(departId, today);
            JSONObject jsonResult = new JSONObject();
            jsonResult.put("departName", departName);
            jsonResult.put("departId", departId);
            jsonResult.put("shouldCount", Integer.valueOf(departJsonObject.get("shouldCount").toString()));
            jsonResult.put("signInCount", Integer.valueOf(departJsonObject.get("signInCount").toString()));
            jsonResult.put("leaveCount", Integer.valueOf(departJsonObject.get("leaveCount").toString()));
            Integer lackCount = Integer.valueOf(departJsonObject.get("shouldCount").toString()) - Integer.valueOf(departJsonObject.get("signInCount").toString()) - Integer.valueOf(departJsonObject.get("leaveCount").toString());
            jsonResult.put("lackCount", lackCount < 0 ? 0 : lackCount);
            list.add(jsonResult);
        }
        return list;
    }


    /**
     * 公司管理层：某个月
     *
     * @param jsonObject
     * @return
     */
    @Override
    public List<JSONObject> getSignInDepartManagerList(JSONObject jsonObject) {
        String companyId = jsonObject.get("companyId").toString();
        String signInMonth = jsonObject.get("signInMonth").toString();
        //返回的集合
        List<JSONObject> list = new ArrayList<>();
        //当前日期
        Calendar c = Calendar.getInstance();
        String today = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        List<JSONObject> userList = signInDao.getUserListByCompany(companyId);
        //销售部考勤
        for (JSONObject regionJson : userList.stream().filter(x -> x.get("parentId").toString().equals("")).collect(Collectors.toList())) {
            JSONObject json = new JSONObject();
            String userId = regionJson.get("userId").toString();
            json.put("departName", regionJson.get("departName").toString());
            json.put("regionName", "-");
            json.put("roleName", regionJson.get("roleName").toString());
            json.put("name", regionJson.get("userName").toString());
            json.put("userId", userId);
            if (!StringUtils.isBlank(userId)) {
                JSONObject userJson = userDao.getViewJSONById(userId);
                JSONObject signInObject = signInDao.getSignInByUserId(userId, userJson.get("roleId").toString(), signInMonth, today);
                Integer shouldCount = Integer.valueOf(signInObject.get("shouldCount").toString());
                json.put("shouldCount", shouldCount);
                json.put("signInCount", Integer.valueOf(signInObject.get("signInCount").toString()));
                json.put("leaveCount", Integer.valueOf(signInObject.get("leaveCount").toString()));
                Integer lackCount = shouldCount - Integer.valueOf(signInObject.get("signInCount").toString()) - Integer.valueOf(signInObject.get("leaveCount").toString());
                json.put("lackCount", lackCount < 0 ? 0 : lackCount);
            }
            list.add(json);
        }
        //大区考勤
        for (JSONObject valJson : userList.stream().filter(x -> x.get("parentId").toString().equals("0")).collect(Collectors.toList())) {
            if (valJson.get("regionName").equals("大客户")) {
                continue;
            }
            for (JSONObject regionJson : userList.stream().filter(x -> x.get("parentId").toString().equals(valJson.get("regionId")) || x.get("regionId").toString().equals(valJson.get("regionId"))).collect(Collectors.toList())) {
                JSONObject json = new JSONObject();
                String userId = regionJson.get("userId").toString();
                if (regionJson.get("parentId").toString().equals("0")) {
                    json.put("departName", regionJson.get("regionName").toString());
                } else if (!regionJson.get("parentId").toString().equals("")) {
                    json.put("departName", userList.stream().filter(x -> x.get("regionId").toString().equals(regionJson.get("parentId").toString())).collect(Collectors.toList()).get(0).get("regionName").toString());
                }
                json.put("regionName", regionJson.get("regionName").toString());
                json.put("roleName", regionJson.get("parentId").toString().equals("0") ? "大区经理" : "区域经理");
                json.put("name", !regionJson.get("userName").toString().equals("") ? regionJson.get("userName").toString() : "空缺");
                json.put("userId", userId);
                if (!StringUtils.isBlank(userId)) {
                    JSONObject userJson = userDao.getViewJSONById(userId);
                    JSONObject signInObject = signInDao.getSignInByUserId(userId, userJson.get("roleId").toString(), signInMonth, today);
                    Integer shouldCount = 0;
                    if (!signInObject.get("shouldCount").toString().equals("")) {
                        shouldCount = Integer.valueOf(signInObject.get("shouldCount").toString());
                    }
                    json.put("shouldCount", shouldCount);
                    json.put("signInCount", Integer.valueOf(signInObject.get("signInCount").toString()));
                    json.put("leaveCount", Integer.valueOf(signInObject.get("leaveCount").toString()));
                    Integer lackCount = shouldCount - Integer.valueOf(signInObject.get("signInCount").toString()) - Integer.valueOf(signInObject.get("leaveCount").toString());
                    json.put("lackCount", lackCount < 0 ? 0 : lackCount);
                }
                list.add(json);
            }
        }
        return list;
    }

    /**
     * 公司管理层：部门详细或大区详细
     *
     * @param jsonObject
     * @return
     */
    @Override
    public List<JSONObject> getSignInDepartDetail(JSONObject jsonObject) {
        String departId = jsonObject.get("departId").toString();
        String isRegionDepart = "0";
        if (!StringUtils.isBlank(jsonObject.getString("isRegionDepart"))) {
            isRegionDepart = jsonObject.get("isRegionDepart").toString();
        } else {
            //获取部门名称
            DepartEntity departEntity = departDao.getById(departId);
            if (departEntity.getName().contains("大区")) {
                isRegionDepart = "1";
            }
        }
        //返回的集合
        List<JSONObject> list = new ArrayList<>();
        //当前日期
        Calendar c = Calendar.getInstance();
        String today = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        if (isRegionDepart.equals("0")) {
            List<JSONObject> userList = signInDao.getSalerDepartUserList(departId);
            for (Integer i = 0; i < userList.size(); i++) {
                JSONObject json = new JSONObject();
                String userId = userList.get(i).get("userId").toString();
                json.put("departName", userList.get(i).get("departName").toString());
                json.put("regionName", "");
                json.put("roleName", userList.get(i).get("roleName").toString());
                json.put("name", userList.get(i).get("userName").toString());
                json.put("userId", userId);
                list.add(json);
            }
        } else if (isRegionDepart.equals("1")) {
            //获取某个大区经理和区域经理
            List<JSONObject> userList = signInDao.getRegionListByBigRegionDepartId(departId);
            for (Integer i = 0; i < userList.size(); i++) {
                JSONObject json = new JSONObject();
                json.put("departName", "");
                json.put("regionName", userList.get(i).get("regionName").toString());
                json.put("roleName", userList.get(i).get("managerRoleName").toString());
                json.put("name", userList.get(i).get("managerName").toString());
                json.put("userId", userList.get(i).get("managerId").toString());
                list.add(json);
            }
        }
        //获取考勤信息（当天）
        for (Integer i = 0; i < list.size(); i++) {
            String userId = list.get(i).get("userId").toString();
            JSONObject json = list.get(i);
            //获取签到信息，今天
            String signState = "";
            List<JSONObject> signInList = signInDao.getJSONListByCondition("AND SIGN_DATE = ? AND USER_ID = ?", new Object[]{today, userId});
            if (signInList.size() > 0) {
                signState = "0";//正常
                json.put("createTime", DateUtils.parse((Date) signInList.get(0).get("createTime"), "HH:mm"));
                json.put("address", signInList.get(0).get("address"));
                if (!StringUtils.isBlank(signInList.get(0).get("signOutTime").toString())) {
                    json.put("signOutTime", DateUtils.parse((Date) signInList.get(0).get("signOutTime"), "HH:mm"));
                    json.put("signOutAddress", signInList.get(0).get("signOutAddress"));
                }
            }
            if (signState.equals("")) {
                //获取请假信息
                List<JSONObject> leaveList = leaveDao.getJSONListByCondition(" AND LEAVE_DATE = ? AND USER_ID = ?", new Object[]{today, userId});
                if (leaveList.size() > 0) {
                    signState = "1";//请假
                    json.put("remark", leaveList.get(0).get("remark").toString());
                }
            }
            if (signState.equals("")) {
                signState = "2";//缺勤
            }
            json.put("signState", signState);
        }
        return list;
    }

    /**
     * 集团管理层：获取所有公司考勤统计
     *
     * @return
     */
    @Override
    public List<JSONObject> getSignInCompanyManagerList(JSONObject jsonObject) {
        String signInMonth = jsonObject.get("signInMonth").toString();
        String isToday = jsonObject.get("isToday").toString();
        //当前日期
        Calendar c = Calendar.getInstance();
        String today = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        //返回的集合
        List<JSONObject> list = new ArrayList<>();
        //所有公司
        List<JSONObject> companyList = companyDao.getJSONListByCondition(" AND DEL_FLAG=0  ORDER BY SORT_NO ", null);
        for (Integer i = 0; i < companyList.size(); i++) {
            String companyId = companyList.get(i).get("id").toString();
            String companyName = companyList.get(i).get("name").toString();
            JSONObject jsonResult = new JSONObject();
            jsonResult.put("companyName", companyName);
            jsonResult.put("companyId", companyId);
            JSONObject companyJsonObject = new JSONObject();
            if (isToday.equals("1")) {
                //获取某个部门今天的考勤汇总
                companyJsonObject = signInDao.getSignInByCompany(companyId, today);

            } else {
                companyJsonObject = signInDao.getSignInCompanyTotal(companyId, signInMonth);
            }
            jsonResult.put("shouldCount", Integer.valueOf(companyJsonObject.get("shouldCount").toString()));
            jsonResult.put("signInCount", Integer.valueOf(companyJsonObject.get("signInCount").toString()));
            jsonResult.put("leaveCount", Integer.valueOf(companyJsonObject.get("leaveCount").toString()));
            Integer lackCount = Integer.valueOf(companyJsonObject.get("shouldCount").toString()) - Integer.valueOf(companyJsonObject.get("signInCount").toString()) - Integer.valueOf(companyJsonObject.get("leaveCount").toString());
            jsonResult.put("lackCount", lackCount < 0 ? 0 : lackCount);
            list.add(jsonResult);
        }
        return list;
    }

    /**
     * 获取考勤跳转到的页面
     *
     * @return
     */
    @Override
    public JSONObject getGotoSignIn(JSONObject json) {
        JSONObject jsonObject = signInDao.getUserParent(json.get("userId").toString());
        JSONObject jsonResult = new JSONObject();
        //是否有下级
        Integer childrenCount = Integer.valueOf(jsonObject.get("childrenCount").toString());
        jsonResult.put("gotoState", childrenCount == 0 ? "0" : "");
        return jsonResult;
    }

    /**
     * 获取签到和首次/末次拜访差距信息
     * <p>
     * //参数传入signOutAddress不为空时,执行末次拜访
     */
    @Override
    public JSONObject saveFirstOrLastVisitDiff(String jsonData) {
        return signInDao.saveFirstOrLastVisitDiff(jsonData);
    }
}
